package com.zw.mizhe.common.base.mvp;

import android.support.annotation.UiThread;

import java.lang.ref.Reference;
import java.lang.ref.WeakReference;

import rx.Subscription;
import rx.subscriptions.CompositeSubscription;

/**
 * Created by zhangwei on 16/10/21.
 */

public abstract class BasePresenter<IV extends BaseView> {
    Reference<IV> mViewRef;//View接口类型的弱引用
    CompositeSubscription mCompositeSubscription;

    @UiThread
    public void attachView(IV v) {
        mViewRef = new WeakReference<>(v);
    }

    public IV getView() {
        return mViewRef.get();
    }

    public boolean isAttchView() {
        return mViewRef != null && mViewRef.get() != null;
    }

    @UiThread
    public void detachView() {
        onUnsubscribe();
        if (mViewRef != null) {
            mViewRef.clear();
            mViewRef = null;
        }
    }

    public static class MvpViewNotAttachedException extends RuntimeException {
        public MvpViewNotAttachedException() {
            super("Please call Presenter.attachView(MvpView) before" +
                    " requesting data to the Presenter");
        }
    }


    //RXjava取消注册，以避免内存泄露
    public void onUnsubscribe() {
        if (mCompositeSubscription != null && mCompositeSubscription.hasSubscriptions()) {
            mCompositeSubscription.unsubscribe();
        }
    }

    //RXjava注册
    public void addSubscription(Subscription subscriber) {
        if (mCompositeSubscription == null) {
            mCompositeSubscription = new CompositeSubscription();
        }
        mCompositeSubscription.add(subscriber);
    }
}